//
//  Topic_getTopicList_tv_ad_cell.m
//  ainkjj
//
//  Created by MAX on 2020/5/6.
//  Copyright © 2020 zhiyiLiu. All rights reserved.
//

#import "Topic_getTopicList_tv_ad_cell.h"
#import "UIButton+WebCache.h"
#import <SafariServices/SafariServices.h>
static UIEdgeInsets const kInsets = {30, 32, 30, 32};
static CGSize const kAvatarSize = {10, 12};
static CGFloat const  kAvatarMarginRight = 10;
static CGFloat const  kAvatarMarginBottom = 12;
static CGFloat const  kContentMarginBotom = 12;

@implementation Topic_getTopicList_tv_ad_cell

- (void)didInitializeWithStyle:(UITableViewCellStyle)style {
    [super didInitializeWithStyle:style];
    [self setSelectionStyle:UITableViewCellSelectionStyleNone];
    self.contentView.backgroundColor = UIColor.groupTableViewBackgroundColor;
    _bgV = [UIView new];
    [self.contentView addSubview:_bgV];
    _bgV.backgroundColor = UIColor.whiteColor;
    _bgV.layer.masksToBounds = YES;
    _bgV.layer.cornerRadius = 5;
    
    _avatarImageView = [[UIImageView alloc] init];
    [self.contentView addSubview:self.avatarImageView];
    
    _nameLabel = [[UILabel alloc] qmui_initWithFont:UIFontBoldMake(16) textColor:rgb(17,17,17)];
    [self.contentView addSubview:self.nameLabel];
    _nameLabel.textColor = rgb(91,132,227);
  
    _x_btn = [UIButton new];
    [self.contentView addSubview:_x_btn];
    [_x_btn setImage:UIImageMake(@"close_icon") forState:UIControlStateNormal];
    [_x_btn addTarget:self action:@selector(x_btn_action:) forControlEvents:UIControlEventTouchUpInside];

    
    self.separatorLayer1 = [QDCommonUI generateSeparatorLayer];
    [self.contentView.layer addSublayer:self.separatorLayer1];
    
    
    _v1 = [UIButton new];
    [self.contentView addSubview:_v1];
    _v2 = [UIButton new];
    [self.contentView addSubview:_v2];
    _v3 = [UIButton new];
    [self.contentView addSubview:_v3];
    self.vArr = @[_v1, _v2, _v3];
    
    for (UIButton *v in self.vArr) {
        v.layer.cornerRadius = 5;
        v.layer.masksToBounds = YES;
        [v addTarget:self action:@selector(click:) forControlEvents:UIControlEventTouchUpInside];
        v.userInteractionEnabled = NO;
    }
    
   
}

- (void)click:(UIButton *)sender{
    NSInteger idx = [self.vArr indexOfObject:sender];
    Topic_getTopicListAdmanage *ad = self.model.adManage[idx];
    NSURL *url = [NSURL URLWithString:ad.url];//     NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"tbopen://%@", [ad.url stringByReplacingOccurrencesOfString:@"http://" withString:@""]]];

    
    // 默认处理为淘宝的链接
    if ([ad.url containsString:@"taobao"] || [ad.url containsString:@"tb.cn"] || [ad.url containsString:@"tmall"]) {
        NSString *rawUrl = [ad.url stringByReplacingOccurrencesOfString:@"https://" withString:@""];
        rawUrl  = [rawUrl stringByReplacingOccurrencesOfString:@"http://" withString:@""];
        url = [NSURL URLWithString:[NSString stringWithFormat:@"tbopen://%@", rawUrl]];
        
    }
    
//    NSURL *ad_url = [NSURL URLWithString:[NSString stringWithFormat:@"tbopen://%@", [ad.url stringByReplacingOccurrencesOfString:@"https://" withString:@""]]];
//    url = ad_url;
    if ([[UIApplication sharedApplication] canOpenURL:url]){
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {}];
        
    }else{
        SFSafariViewController *vc = [[SFSafariViewController alloc] initWithURL:[NSURL URLWithString:ad.url]];
        [[Anktool viewControllerForView:self] presentViewController:vc animated:YES completion:nil];
    }
}

- (NSAttributedString *)attributeStringWithString:(NSString *)textString lineHeight:(CGFloat)lineHeight {
    if (textString.qmui_trim.length <= 0) return nil;
    NSAttributedString *attriString = [[NSAttributedString alloc] initWithString:textString attributes:@{NSParagraphStyleAttributeName:[NSMutableParagraphStyle qmui_paragraphStyleWithLineHeight:lineHeight lineBreakMode:NSLineBreakByCharWrapping textAlignment:NSTextAlignmentLeft]}];
    return attriString;
}

- (CGSize)sizeThatFits:(CGSize)size {
    CGSize resultSize = CGSizeMake(size.width, 0);
    CGFloat contentLabelWidth = size.width - UIEdgeInsetsGetHorizontalValue(kInsets);
    
    CGFloat resultHeight = UIEdgeInsetsGetHorizontalValue(kInsets) + CGRectGetHeight(self.avatarImageView.bounds) + kAvatarMarginBottom;
    
    
    
    // 图片固定布局
    CGFloat ivW = (ScreenWidth - kInsets.left - kInsets.right - 7 * 2) / 3.0;
    CGFloat ivH = ivW * 46 / 100.0;
    
    
    resultHeight += 10;
    
    if (self.model.adManage.count > 0) {
        resultHeight += ivH + 26;
    }
    
//    resultHeight += kAvatarMarginBottom;

    
    resultSize.height = resultHeight + 6;
//    NSLog(@"%@ 的 cell 的 sizeThatFits: 被调用（说明这个 cell 的高度重新计算了一遍）", self.nameLabel.text);
    return resultSize;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    CGFloat contentLabelWidth = CGRectGetWidth(self.contentView.bounds) - UIEdgeInsetsGetHorizontalValue(kInsets);
    self.avatarImageView.frame = CGRectMake(kInsets.left, kInsets.top - 10, kAvatarSize.width, kAvatarSize.height);
    if (self.nameLabel.text.length > 0) {
        CGFloat nameLabelWidth = contentLabelWidth - CGRectGetWidth(self.avatarImageView.bounds) - kAvatarMarginRight - 44;
        CGSize nameSize = [self.nameLabel sizeThatFits:CGSizeMake(nameLabelWidth, CGFLOAT_MAX)];
        self.nameLabel.frame = CGRectFlatMake(CGRectGetMaxX(self.avatarImageView.frame) + kAvatarMarginRight, CGRectGetMinY(self.avatarImageView.frame) - 3, nameLabelWidth, nameSize.height);
    }
    
    self.x_btn.frame = CGRectMake(contentLabelWidth  , 8, 44, 44);
    

    
    // 图片固定布局
    CGFloat ivW = (ScreenWidth - kInsets.left - kInsets.right - 7 * 2) / 3.0;
    CGFloat ivH = ivW * 84 / 100.0;
    for (NSInteger i = 0; i < self.vArr.count; i++) {
        UIButton *iv = self.vArr[i];
        iv.frame = CGRectMake( kInsets.left + i * (ivW + 7), CGRectGetMaxY(self.avatarImageView.frame) + 26, ivW, ivH);
    }
    
   
    
    self.bgV.frame = CGRectMake(kInsets.left * 0.5, kInsets.top * 0.25, ScreenWidth - kInsets.left, CGRectGetMaxY(self.v1.frame) + 6);
    self.separatorLayer1.frame = CGRectMake( CGRectGetMinX(self.bgV.frame), CGRectGetMaxY(self.avatarImageView.frame) + PixelOne + kAvatarMarginBottom, CGRectGetWidth(self.bgV.frame) , PixelOne);

}
- (void)setModel:(Topic_getTopicListData *)model{
    _model = model;
    
    [self.avatarImageView setImage:UIImageMake(@"hot_icon")];
    self.nameLabel.text = @"好物推荐";
  
    
    // 图片赋值，如果有就赋值，没有就赋值为空
    NSUInteger imgCount = MIN(3, model.adManage.count);
    for (NSInteger i = 0; i < imgCount; i++) {
        UIButton *v = self.vArr[i];
        if (i < imgCount) {
            Topic_getTopicListAdmanage *ad = model.adManage[i];
            [v sd_setImageWithURL:[NSURL URLWithString:ad.pic] forState:UIControlStateNormal];
            v.userInteractionEnabled = YES;
        }else{
            [v setImage:nil forState:UIControlStateNormal];
            v.userInteractionEnabled = NO;

        }
    }
    
}
- (void)x_btn_action:(UIButton *)sender{
    sender.userInteractionEnabled = NO;
    
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:app_code forKey:@"appCode"];
    [dict setObject:AuthSignin_model.sharedInstance.data.token forKey:@"token"];
    NSMutableArray *keys = NSMutableArray.new;
    for (Topic_getTopicListAdmanage *ad in self.model.adManage) {
        [keys addObject:@(ad.ID).stringValue];
    }
    [dict setObject:[keys componentsJoinedByString:@","] forKey:@"topicId"];
    
    //sender.userInteractionEnabled = NO;
    
    
    [PPHTTPRequest req:@"java/app/adManage/adShield" parameters:dict success:^(id response) {
        NSString *error_code = [NSString stringWithFormat:@"%@", response[@"error_code"]];
        if ([error_code isEqualToString:@"0"]) {
            if (self.blk) {
                self.blk(self.idxPath);
            }
        }
        else{
            
            [QMUITips showError:response[@"error_msg"] ];
            
        }
        sender.userInteractionEnabled = YES;
    } failure:^(NSError *error) {
        [QMUITips showError:[error localizedDescription] ];
        sender.userInteractionEnabled = YES;
    }];
}
@end

